package com.gzdh.dishrecognition.ali;

import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alipay.iot.bpaas.api.BPaaSApi;
import com.alipay.iot.bpaas.api.service.BPaaSCallback;
import com.alipay.iot.bpaas.api.service.BPaaSResponse;
import com.alipay.iot.bpaas.api.service.LocalService;
import com.gzdh.dishrecognition.config.SystemConfig;

public class AliRead {
    private final String TAG = "AliRead";
    private String mSessionId = "";
    private String mTradeNo = "";

    public interface UserPost {
        void post(int type);
    }

    public void showScanCardPayResult(UserPost userPost) {
        String tag = "mockedCardTag";
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("cardTag", tag);
        Bundle bundle = new Bundle();
        bundle.putString("templateId", SystemConfig.getInstance().getTemplateId());
        bundle.putString("operateType", "requestSession");
        bundle.putString("page", "canteen");
        bundle.putString("templateParams", jsonObject.toJSONString());
        BPaaSApi.getInstance().startBPaaSService(SystemConfig.getInstance().getAbcpApplicationAppid(),
                SystemConfig.getInstance().getTemplateServiceCode(), bundle, new BPaaSCallback() {
                    @Override
                    public void onResponse(BPaaSResponse response) {
                        if (response == null || response.getCode() == BPaaSResponse.RESULT_CODE_FAIL) {
                            // bpaas服务调用失败
                            Log.i(TAG, "bpaas transfer fail");
                        } else if (response.getResult() != null) {
                            Log.i(TAG, "onResponse :" + response);
                            Bundle result = response.getResult().getBundle(LocalService.KEY_LOCAL_RESULT);
                            if (result != null) {
                                // 处理刷脸结果
                                int code = result.getInt("code");
                                if (code == BPaaSResponse.RESULT_CODE_SUCCESS) {
                                    Bundle extInfo = result.getBundle("extInfo");
                                    if (extInfo != null) {
                                        String resultStr = extInfo.getString("result");
                                        if (!TextUtils.isEmpty(resultStr)) {
                                            JSONObject extJson = JSONObject.parseObject(resultStr);
                                            mSessionId = extJson.getString("sessionId");
                                            mTradeNo = extJson.getString("tradeNo");
                                            showCardPayLoadingPage(userPost);
                                        }
                                    }
                                } else {
                                    String subCode = result.getString("subCode");
                                    String subMessage = result.getString("subMsg");
                                    Log.d(TAG, "requestSession fail code = " + code + ",subCode=" + subCode + "..." + "subMessage=" + subMessage);
                                }
                            }
                        }
                    }

                    @Override
                    public void onEvent(String eventId, String data, Bundle extra) {
                        Log.i(TAG, "onEvent eventId:" + eventId + ",data:" + data);
                    }
                });
    }

    private void showCardPayLoadingPage(UserPost userPost) {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("sessionId", mSessionId);
        jsonObject.put("tradeNo", mTradeNo);
        JSONObject advancedConfig = new JSONObject();
        advancedConfig.put("version", "2.0");
        JSONObject outerSummary = new JSONObject();
        outerSummary.put("title", "稍等，正在支付...");
        advancedConfig.put("OuterSummary", outerSummary);
        jsonObject.put("advancedConfig", advancedConfig.toJSONString());
        Bundle bundle = new Bundle();
        bundle.putString("templateId", SystemConfig.getInstance().getTemplateId());
        bundle.putString("operateType", "showCardPayLoadingPage");
        bundle.putString("page", "payResult");
        bundle.putString("templateParams", jsonObject.toJSONString());
        BPaaSApi.getInstance().startBPaaSService(SystemConfig.getInstance().getAbcpApplicationAppid(), SystemConfig.getInstance().getTemplateServiceCode(),
                bundle, new BPaaSCallback() {
                    @Override
                    public void onResponse(BPaaSResponse response) {
                        responseInvoke(response, "showCardPayLoadingPage");
                        userPost.post(1);
                    }

                    @Override
                    public void onEvent(String eventId, String data, Bundle extra) {
                        Log.i(TAG, "onEvent eventId:" + eventId + ",data:" + data);

                    }
                });
    }


    /**
     * 展示刷卡/扫码支付loading页
     */
    public void goCardPayResultError(String errMsg) {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("sessionId", mSessionId);
        jsonObject.put("tradeNo", mTradeNo);
        jsonObject.put("cardTag", "mockedCardTag");
        jsonObject.put("success", false); // 必填，false为支付失败
        jsonObject.put("resultTimeOut", 3); //倒计时

        //TODO 构造你的advancedConfig
        JSONObject outerSummary = new JSONObject();
        outerSummary.put("enablePaymentVoice", true);
        outerSummary.put("title", errMsg);

        JSONObject advancedConfig = new JSONObject();
        advancedConfig.put("version", "2.0");
        advancedConfig.put("OuterSummary", outerSummary);

        jsonObject.put("advancedConfig", advancedConfig.toJSONString());

        Bundle bundle = new Bundle();
        bundle.putString("templateId", SystemConfig.getInstance().getTemplateId());
        bundle.putString("operateType", "showScanCardOfflinePayResult");// 刷卡/扫码都使用这个operateType
        bundle.putString("page", "payResult");
        bundle.putString("templateParams", jsonObject.toJSONString());
        BPaaSApi.getInstance().startBPaaSService(SystemConfig.getInstance().getAbcpApplicationAppid(),
                SystemConfig.getInstance().getTemplateServiceCode(), bundle, new BPaaSCallback() {
                    @Override
                    public void onResponse(BPaaSResponse response) {
                        responseInvoke(response, "showScanCardOfflinePayResult");
                    }

                    @Override
                    public void onEvent(String eventId, String data, Bundle extra) {
                        Log.i(TAG, "onEvent eventId:" + eventId + ",data:" + data);
                        JSONObject response = JSON.parseObject(data);
                        if (response != null) {
                            String eventType = response.getString("messageType");
                            if (eventType.equals("CLOSE")) {
                                //支付结果页已关闭
                                Log.i(TAG, "刷卡支付结果页已关闭");
                            } else if (eventType.equals("ShowSuccess")) {
                                //支付结果页展示成功
                                Log.i(TAG, "刷卡支付结果页展示成功");
                            } else if (eventType.equals("ShowFail")) {
                                //支付结果页展示失败
                                Log.i(TAG, "刷卡支付结果页展示失败");
                            }
                        }
                    }
                });
    }


    public void goCardPayResultSuccess(JSONObject reqJson) {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("sessionId", mSessionId);
        jsonObject.put("tradeNo", mTradeNo);
        jsonObject.put("cardTag", "mockedCardTag");
        jsonObject.put("success", true); // 必填，false为支付失败
        jsonObject.put("resultTimeOut", 3); //倒计时
        JSONObject outerSummary = new JSONObject();
        outerSummary.put("enablePaymentVoice", true);
        outerSummary.put("actualAmount", reqJson.getString("amount"));
        outerSummary.put("title", reqJson.getString("msg"));
        JSONObject advancedConfig = new JSONObject();
        advancedConfig.put("version", "2.0");
        advancedConfig.put("OuterSummary", outerSummary);
        advancedConfig.put("OuterExtends", reqJson.getJSONArray("outerExtends"));
        jsonObject.put("advancedConfig", advancedConfig.toJSONString());
        Bundle bundle = new Bundle();
        bundle.putString("templateId", SystemConfig.getInstance().getTemplateId());
        bundle.putString("operateType", "showScanCardOfflinePayResult");// 刷卡/扫码都使用这个operateType
        bundle.putString("page", "payResult");
        bundle.putString("templateParams", jsonObject.toJSONString());
        BPaaSApi.getInstance().startBPaaSService(SystemConfig.getInstance().getAbcpApplicationAppid(),
                SystemConfig.getInstance().getTemplateServiceCode(), bundle, new BPaaSCallback() {
                    @Override
                    public void onResponse(BPaaSResponse response) {
                        responseInvoke(response, "showScanCardOfflinePayResult");
                    }

                    @Override
                    public void onEvent(String eventId, String data, Bundle extra) {
                        Log.i(TAG, "onEvent eventId:" + eventId + ",data:" + data);
                        JSONObject response = JSON.parseObject(data);
                        if (response != null) {
                            String eventType = response.getString("messageType");
                            if (eventType.equals("CLOSE")) {
                                //支付结果页已关闭
                                Log.i(TAG, "刷卡支付结果页已关闭");
                            } else if (eventType.equals("ShowSuccess")) {
                                //支付结果页展示成功
                                Log.i(TAG, "刷卡支付结果页展示成功");
                            } else if (eventType.equals("ShowFail")) {
                                //支付结果页展示失败
                                Log.i(TAG, "刷卡支付结果页展示失败");
                            }
                        }
                    }
                });
    }


    private void printBPaaSResponse(BPaaSResponse response, String subTag) {
        String ret;
        if (response == null) {
            ret = "response is null";
        } else {
            int code = response.getCode();
            String subCode = response.getSubCode();
            String subMsg = response.getSubMsg();
            Bundle result = response.getResult();

            ret = "code=" +
                    code +
                    ", subCode=" +
                    subCode +
                    ", subMsg=" +
                    subMsg +
                    ", result=" +
                    bundle2JsonString(result);
        }
        Log.d(TAG, "printBPaaSResponse_" + subTag + ":" + ret);
    }

    /**
     * 操作结果处理
     *
     * @param response 响应结果
     * @param tag      操作名称描述
     */
    public void responseInvoke(BPaaSResponse response, String tag) {
        printBPaaSResponse(response, tag);
        if (response == null) {
            Log.e(TAG, "response is null");
            return;
        }

        if (response.getCode() == BPaaSResponse.RESULT_CODE_FAIL) {
            String subCode = response.getSubCode();
            String subMsg = response.getSubMsg();
            // bpaas服务调用失败
            Log.e(TAG, "bpaas transfer fail subCode = " + subCode + ",subMsg = " + subMsg);
        } else if (response.getCode() == BPaaSResponse.RESULT_CODE_SUCCESS) {
            if (response.getResult() != null) {
                Bundle result = response.getResult().getBundle(LocalService.KEY_LOCAL_RESULT);
                if (result != null) {
                    int code = result.getInt("code");
                    Log.i(TAG, "code:" + code);
                    // 操作失败处理 subCode：错误code ，subMessage：错误信息描述
                    Bundle extInfo = result.getBundle("extInfo");
                    if (extInfo != null) {
                        if (extInfo.getBoolean("success")) {
                            // TODO 操作成功处理...
                        } else {
                            String subCode = extInfo.getString("subCode");
                            String subMessage = extInfo.getString("subMessage");
                            Log.e(TAG, tag + " fail result : subCode = " + subCode + ",subMessage = " + subMessage);
                        }
                    }
                }
            }
        } else {
            Log.w(TAG, "response.getCode:" + response.getCode());
        }
    }

    private String bundle2JsonString(Bundle bundle) {
        if (bundle == null) {
            return "null";
        }
        JSONObject ret = new JSONObject();
        for (String key : bundle.keySet()) {
            Object val = bundle.get(key);
            if (val instanceof Bundle) {
                ret.put(key, bundle2JsonString((Bundle) val));
            } else {
                ret.put(key, val);
            }
        }
        return ret.toJSONString();
    }

    public void close(UserPost userPost) {
        Bundle bundle = new Bundle();
        bundle.putString("templateId", SystemConfig.getInstance().getTemplateId());
        bundle.putString("operateType", "close");
        bundle.putString("page", "faceVerify");
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("sessionId", mSessionId);
        bundle.putString("templateParams", jsonObject.toJSONString());
        BPaaSApi.getInstance().startBPaaSService(SystemConfig.getInstance().getAbcpApplicationAppid(),
                SystemConfig.getInstance().getTemplateServiceCode(), bundle, new BPaaSCallback() {
                    @Override
                    public void onResponse(BPaaSResponse response) {
//                responseInvoke(response, "closeScanFace");
                        if (userPost != null) {
                            userPost.post(1);
                        }
                    }

                    @Override
                    public void onEvent(String eventId, String data, Bundle extra) {
                        Log.i(TAG, "onEvent eventId:" + eventId + ",data:" + data);
                    }
                });
    }

    public void goFacePayResultSuccess(JSONObject reqJson) {
        String tag = "mockedCardTag";
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("cardTag", tag);
        Bundle bundle = new Bundle();
        bundle.putString("templateId", SystemConfig.getInstance().getTemplateId());
        bundle.putString("operateType", "requestSession");
        bundle.putString("page", "canteen");
        bundle.putString("templateParams", jsonObject.toJSONString());
        BPaaSApi.getInstance().startBPaaSService(SystemConfig.getInstance().getAbcpApplicationAppid(),
                SystemConfig.getInstance().getTemplateServiceCode(), bundle, new BPaaSCallback() {
                    @Override
                    public void onResponse(BPaaSResponse response) {
                        if (response == null || response.getCode() == BPaaSResponse.RESULT_CODE_FAIL) {
                            // bpaas服务调用失败
                            Log.i(TAG, "bpaas transfer fail");
                        } else if (response.getResult() != null) {
                            Log.i(TAG, "onResponse :" + response);
                            Bundle result = response.getResult().getBundle(LocalService.KEY_LOCAL_RESULT);
                            if (result != null) {
                                // 处理刷脸结果
                                int code = result.getInt("code");
                                if (code == BPaaSResponse.RESULT_CODE_SUCCESS) {
                                    Bundle extInfo = result.getBundle("extInfo");
                                    if (extInfo != null) {
                                        String resultStr = extInfo.getString("result");
                                        if (!TextUtils.isEmpty(resultStr)) {
                                            JSONObject extJson = JSONObject.parseObject(resultStr);
                                            String sessionId = extJson.getString("sessionId");
                                            String tradeNo = extJson.getString("tradeNo");
                                            goFacePayResultSuccess(sessionId, tradeNo, reqJson);
                                        }
                                    }
                                } else {
                                    String subCode = result.getString("subCode");
                                    String subMessage = result.getString("subMsg");
                                    Log.d(TAG, "requestSession fail code = " + code + ",subCode=" + subCode + "..." + "subMessage=" + subMessage);
                                }
                            }
                        }
                    }

                    @Override
                    public void onEvent(String eventId, String data, Bundle extra) {
                        Log.i(TAG, "onEvent eventId:" + eventId + ",data:" + data);
                    }
                });
    }


    public void goFacePayResultSuccess(String sessionId, String tradeNo, JSONObject reqJson) {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("sessionId", sessionId);
        jsonObject.put("tradeNo", tradeNo);
        jsonObject.put("cardTag", "mockedCardTag");
        jsonObject.put("success", true); // 必填，false为支付失败
        jsonObject.put("resultTimeOut", 3); //倒计时
        JSONObject outerSummary = new JSONObject();
        outerSummary.put("enablePaymentVoice", true);
        outerSummary.put("actualAmount", reqJson.getString("amount"));
        outerSummary.put("title", reqJson.getString("msg"));
        JSONObject advancedConfig = new JSONObject();
        advancedConfig.put("version", "2.0");
        advancedConfig.put("OuterSummary", outerSummary);
        advancedConfig.put("OuterExtends", reqJson.getJSONArray("outerExtends"));
        jsonObject.put("advancedConfig", advancedConfig.toJSONString());
        Bundle bundle = new Bundle();
        bundle.putString("templateId", SystemConfig.getInstance().getTemplateId());
        bundle.putString("operateType", "showScanFaceOfflinePayResult");// 刷卡/扫码都使用这个operateType
        bundle.putString("page", "payResult");
        bundle.putString("templateParams", jsonObject.toJSONString());
        BPaaSApi.getInstance().startBPaaSService(SystemConfig.getInstance().getAbcpApplicationAppid(),
                SystemConfig.getInstance().getTemplateServiceCode(), bundle, new BPaaSCallback() {
                    @Override
                    public void onResponse(BPaaSResponse response) {
                        responseInvoke(response, "showScanCardOfflinePayResult");
                    }

                    @Override
                    public void onEvent(String eventId, String data, Bundle extra) {
                        Log.i(TAG, "onEvent eventId:" + eventId + ",data:" + data);
                        JSONObject response = JSON.parseObject(data);
                        if (response != null) {
                            String eventType = response.getString("messageType");
                            if (eventType.equals("CLOSE")) {
                                //支付结果页已关闭
                                Log.i(TAG, "刷卡支付结果页已关闭");
                            } else if (eventType.equals("ShowSuccess")) {
                                //支付结果页展示成功
                                Log.i(TAG, "刷卡支付结果页展示成功");
                            } else if (eventType.equals("ShowFail")) {
                                //支付结果页展示失败
                                Log.i(TAG, "刷卡支付结果页展示失败");
                            }
                        }
                    }
                });
    }
}
